package ua.yandex.skipasssystem;

import ua.yandex.collections.MyLinkedList;
import ua.yandex.skipasssystem.skipass.SkiPass;
import ua.yandex.skipasssystem.skipass.SkiPassMaker;

import java.time.LocalDateTime;


public class SkiPassSystem implements SkiPassSystemInterface {

    private MyLinkedList skiPassList = new MyLinkedList();
    private MyLinkedList denies = new MyLinkedList();
    private MyLinkedList permissions = new MyLinkedList();
    private SkiPassMaker skiPassMaker = new SkiPassMaker(this);

    private SkiPassSystem() {
    }

    public static SkiPassSystem getSkiPassSystem() {
        return SkiPassSystemHolder.SKI_PASS_SYSTEM_HOLDER;
    }

    @Override
    public SkiPassMaker getSkiPassMaker() {
        return skiPassMaker;
    }

    @Override
    public boolean validateSkiPass(SkiPass skiPass,
                                   LocalDateTime dateTime) {

        boolean isWorkAtDateTime =
                skiPass.getValidator().validate(skiPass,
                        dateTime);
        if (isWorkAtDateTime) {
            permissions.add(skiPass);
        } else {
            denies.add(skiPass);
        }

        return isWorkAtDateTime;
    }

    @Override
    public int getNumberOfDeniesByType(Class skiPassType) {
        int numberOfDenies = 0;
        Object[] deniesArray = denies.toArray();
        for (Object obj : deniesArray) {
            if (obj.getClass().equals(skiPassType)) {
                numberOfDenies++;
            }
        }
        return numberOfDenies;
    }

    @Override
    public int getNumberOfPermissionsByType(Class skiPassType) {
        int numberOfPermissions = 0;
        Object[] permissionsArray = permissions.toArray();
        for (Object obj : permissionsArray) {
            if (obj.getClass().equals(skiPassType)) {
                numberOfPermissions++;
            }
        }
        return numberOfPermissions;
    }

    @Override
    public SkiPass getSkiPass(long id) {
        return (SkiPass) (skiPassList.get((int) id));
    }

    @Override
    public void addSkiPass(SkiPass skiPass) {
        skiPassList.add(skiPass);
    }

    @Override
    public void deactivateSkiPass(long id) {
        ((SkiPass) (skiPassList.get((int) id))).setActive(false);
    }

    @Override
    public int getAllNumberOfPermissions() {
        return permissions.size();
    }

    @Override
    public int getAllNumberOfDenies() {
        return denies.size();
    }

    @Override
    public long getNewSkiPassId() {
        return skiPassList.size();
    }

    public static class SkiPassSystemHolder {
        public static final SkiPassSystem SKI_PASS_SYSTEM_HOLDER
                = new SkiPassSystem();
    }
}

